import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Rectangle;
import flash.geom.Point;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.display.Sprite;
import flash.ui.Keyboard;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import flash.filters.GlowFilter;
import haxe.FastList; 
import flash.display.Shape;
import flash.events.MouseEvent;
import flash.events.EventDispatcher;
import TextArea;
import PauseMenu;
import FadingText;
import CustomSprite;
import GenericMenu;
import WorkCoMenu;
import PopUp;
import PopUpText;
import AchievementBox;

import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.net.SharedObject;
import haxe.remoting.AMFConnection;

//import haxe.Timer;
import flash.events.Event;
import HelperMethods;

import Images;  
import Blob;
import Sounds;
import Button;
import WallStreetMenu;
import CharityMenu;
import Kongregate;

//CharacterStat class small and indepedent, adding a part of scene file.
class IncomeMethod{
 public var Value:  Int;
 public var Money:  Int;
 public var RandomMoney: Int;
 public var PeopleHelped : Int;
 public var RandomPeopleHelped:Int;
 public var Lengivity : Int;
 public var Title : String;
 public var next : IncomeMethod;
	public function new(){
        Value = 0; Money = 0;RandomMoney=0;PeopleHelped=0;RandomPeopleHelped=0;
        Lengivity = 1;next = null;
    }
}
class IncomeMethodContainer extends List<IncomeMethod>{
public function new()
{
super();
}
}



class CharacterStat extends EventDispatcher{
   private var _money : Int;
   private var _billons : Int;
   public var _peopleHelped : Int;
   public var Income : IncomeMethodContainer;

//var biteSound:Bite; 
	public function new(){
          super();
          Income = new IncomeMethodContainer();

    }
   public function getBillions()
   {
     return _billons;
   }
   public var Money(getMoney,setMoney): Int;
   public function getMoney():Int
    {
      if(_money < 500000000 && _billons >= 1)
        {
          _billons--;
          _money = _money + 1000000000;
        }
      return _money;
    }
      public function setMoney(inMoney:Int):Int
    {
      _money = inMoney;
      if(_money >= 1500000000)
         {
	  _money = _money - 1000000000;
	  _billons++;
	  }
   
      dispatchEvent(new Event("updateValues",true,false));
      return inMoney;
    }
      public function setMoneyWithoutEvent(inMoney:Int):Int
    {
      _money += inMoney;
      if(_money >= 1500000000)
         {
	  _money = _money - 1000000000;
	  _billons++;
	  }
   
      return inMoney;
    }
   public function update()
   {
    dispatchEvent(new Event("updateValues",true,false));
   }
   public var PeopleHelped(getPeopleHelped,setPeopleHelped): Int;
   public function getPeopleHelped():Int
    {
      return _peopleHelped;
    }
      public function setPeopleHelped(inPeopleHelped:Int):Int
    {
      _peopleHelped = inPeopleHelped;
      dispatchEvent(new Event("updateValues",true,false));
      return inPeopleHelped;
    }
      public function setPeopleHelpedWithoutEvent(inPeopleHelped:Int):Int
    {
      _peopleHelped += inPeopleHelped;
      
      return inPeopleHelped;
    }
   
   
}

class Scene extends CustomSprite 
{
  public var numOfTurns : Int;
  public static inline var TotalTurns = 150;
  public var Player : CharacterStat;
  public var currentBackground : CustomSprite;
  public var backgroundLayer : CustomSprite;
  private var BackButton:Sprite;
  public var WorkCoButton: CustomSprite;
  public var WorkCoMenuItem : GenericMenu;
  public var WallStreetButton : CustomSprite;
  public var WallStreetMenuItem : WallStreetMenu;
  public var CharityButton : CustomSprite;
  public var CharityMenuItem : CharityMenu;
  public var searchedForJob : Bool;
  public var OkPopUp : PopUp;
  public var OkPopUpText : PopUpText;
  public var SmallFortune : AchievementBox;
  public var Fortune : AchievementBox;
  public var SmallCountry : AchievementBox;
  public var BlackAchievements:List<String>;
  public var KindHearted : AchievementBox;
  public var DecreasedWorldSuck : AchievementBox;
  public var SaveTheWorld : AchievementBox;
  public var WhiteAchievements:List<String>;
  public var PerfectPair : AchievementBox;
  public var MoreThanBalance : AchievementBox;
  public var BothAchievements:List<String>;

  public var achievementNoise:AchievementNoise; 

  private var ignoreKeyPress : String;
  public var Ratio:Float;
  

  public var text : String;
  var mKeyDown:Array<Bool>;
  var lastUp:Int;
  var Pause:String;
  public var volume:Bool;
  public var sound:Bool;
  public var running:Bool;
  public var victory:String;
  public var TurnLeft:TextField;
  public var PlayerStat:TextField;
  public var playersMoney:TextField;
  public var playersPeopleHelped:TextField;
  public var swedishBankAccount:TextField;
  var myTimer:Timer;
  var State:String;
  var PauseTillKeyPressed:Bool;
  var MenuUp:Bool;
  var label1:TextField;
  //var labelBackground:Sprite;
  var NOButton:Sprite;
  var YesButton:Sprite;
  var textBackgroundImage:Sprite;
 
public var pauseMenu:PauseMenu;
var pauseMenuPoint:Point;


public var kongVar : CKongregate;
public var RecievedAchievements:Achievements;

public var EndGame:Sprite;
public var EndGameMoneyEarned:TextField;
public var EndGamePeopleHelped:TextField;
public var EndGameRetry:Sprite;
public var EndGameMainMenu:Sprite;

  public function new(inBackground:BitmapData)
  {
//Need to RegisterMethods inOrder to Save
  haxe.remoting.AMFConnection.registerClassAlias("CharacterStatAlias",CharacterStat);
  haxe.remoting.AMFConnection.registerClassAlias("IncomeMethodAlias",IncomeMethod); 
  haxe.remoting.AMFConnection.registerClassAlias("IncomeMethodContainerAlias",IncomeMethodContainer); 


  super();
   //
  achievementNoise = new AchievementNoise();
   numOfTurns = 0;

   searchedForJob = false;

 //old determine what to use
  pauseMenu = new PauseMenu();
  pauseMenuPoint = new Point(0,370);

  running = false;
  victory = "None";
  Pause = "UnPaused";
  volume = true;
  sound = true;

  State = "Calc"; 
  ignoreKeyPress = "";
 PauseTillKeyPressed = false;

  Ratio = .50;
  //money/(money + people)
//   currentBackground.graphics.beginBitmapFill(inBackground.clone());
//   currentBackground.graphics.drawRect(0, 0, inBackground.width,inBackground.height);
    backgroundLayer = new CustomSprite();
    currentBackground = new CustomSprite();
    backgroundLayer.addChild(currentBackground);
    
  drawBackground();


  


  WorkCoButton = new CustomSprite();
  WorkCoButton.graphics.beginBitmapFill(inBackground.clone());
  WorkCoButton.graphics.drawRect(0, 0, inBackground.width,inBackground.height);
  WorkCoButton.resize(100,100);
  WorkCoButton.buttonMode = true;
  WorkCoButton.x = 50; WorkCoButton.y = 50;

  WorkCoMenuItem = new WorkCoMenu(new Menu());

  WallStreetButton = new CustomSprite();
  WallStreetButton.graphics.lineStyle(1,0xFFFFFF);
  WallStreetButton.graphics.drawRect(0, 0,100,100);
  WallStreetButton.graphics.beginFill(0x000000);

  WallStreetButton.graphics.beginBitmapFill(new Money());
  WallStreetButton.graphics.drawRect(0, 0, 100,100);
  WallStreetButton.resize(100,100);
  WallStreetButton.buttonMode = true;
  WallStreetButton.graphics.endFill();

  WallStreetButton.x = 20; WallStreetButton.y = 50;

  WallStreetMenuItem = new WallStreetMenu(new Menu());

  CharityButton  = new CustomSprite();
  CharityButton.graphics.lineStyle(1);
  CharityButton.graphics.drawRect(0, 0,100,100);
  CharityButton.graphics.beginFill(0xFFFFFF);

  CharityButton.graphics.beginBitmapFill(new CharityPerson());
  CharityButton.graphics.drawRect(0, 0, 100,100);
  CharityButton.resize(100,100);
  CharityButton.buttonMode = true;
  CharityButton.x = 500; CharityButton.y = 270;

  CharityMenuItem = new CharityMenu(new Menu());
  
  OkPopUp = new PopUp(inBackground.clone(),"Test Message");
  OkPopUpText = new PopUpText(inBackground.clone(),"Test Message");
  BlackAchievements = new List<String>();

  SmallFortune = new AchievementBox("SmallFortune");
  SmallFortune.x = 20; SmallFortune.y = 260;
  SmallFortune.text.htmlText = "<font color='#FFFFFF'>Have $10 Million+ in Cash.</font>";
  SmallFortune.title.htmlText = "<font size = '14' color='#FFFFFF'><u>Achievement Unlocked</u> Small Fortune</font>";
  SmallFortune.Icon.graphics.beginBitmapFill(new Money1());
  SmallFortune.Icon.graphics.drawRect(0, 0, 50 ,50);

  Fortune = new AchievementBox("Fortune");
  Fortune.x = 20; Fortune.y = 260;
  Fortune.text.htmlText = "<font color='#FFFFFF'>Have $500 Million+ in Cash.</font>";
  Fortune.title.htmlText = "<font size = '14' color='#FFFFFF'><u>Achievement Unlocked</u> Fortune</font>";
  Fortune.Icon.graphics.beginBitmapFill(new Money2());
  Fortune.Icon.graphics.drawRect(0, 0, 50 ,50);

  SmallCountry = new AchievementBox("SmallCountry");
  SmallCountry.x = 20; SmallCountry.y = 260;
  SmallCountry.text.htmlText = "<font color='#FFFFFF'>Have $3 Billion+ in Cash.</font>";
  SmallCountry.title.htmlText = "<font size = '14' color='#FFFFFF'><u>Achievement Unlocked</u> Small Country</font>";
  SmallCountry.Icon.graphics.beginBitmapFill(new Money3());
  SmallCountry.Icon.graphics.drawRect(0, 0, 50 ,50);

  KindHearted = new AchievementBox("KindHearted");
  KindHearted.x = 370; KindHearted.y = 50;
  KindHearted.text.htmlText = "<font color='#000000'>Help 100,000 People.</font>";
  KindHearted.title.htmlText = "<font size = '14' color='#000000'><u>Achievement Unlocked</u> Kind Hearted</font>";
  KindHearted.TextBackground.graphics.clear();
  KindHearted.TextBackground.graphics.beginFill(0xFFFFFF);
  KindHearted.TextBackground.graphics.lineStyle(1,0x000000);
  KindHearted.TextBackground.graphics.drawRect(0, 0, 235, 100);
  KindHearted.Icon.graphics.clear();
  KindHearted.Icon.graphics.beginFill(0xFFFFFF);
  KindHearted.Icon.graphics.lineStyle(1,0x000000);
  KindHearted.Icon.graphics.drawRect(0, 0, 50, 50);
  KindHearted.Icon.graphics.beginBitmapFill(new Heart1());
  KindHearted.Icon.graphics.drawRect(0, 0, 50 ,50);

  DecreasedWorldSuck = new AchievementBox("DecreasedWorldSuck");
  DecreasedWorldSuck.x = 370; DecreasedWorldSuck.y = 50;
  DecreasedWorldSuck.text.htmlText = "<font color='#000000'>Help 10 million People</font>";
  DecreasedWorldSuck.title.htmlText = "<font size = '14' color='#000000'><u>Achievement Unlocked</u> Decreased World Suck</font>";
  DecreasedWorldSuck.TextBackground.graphics.clear();
  DecreasedWorldSuck.TextBackground.graphics.beginFill(0xFFFFFF);
  DecreasedWorldSuck.TextBackground.graphics.lineStyle(1,0x000000);
  DecreasedWorldSuck.TextBackground.graphics.drawRect(0, 0, 235, 100);
  DecreasedWorldSuck.Icon.graphics.clear();
  DecreasedWorldSuck.Icon.graphics.beginFill(0xFFFFFF);
  DecreasedWorldSuck.Icon.graphics.lineStyle(1,0x000000);
  DecreasedWorldSuck.Icon.graphics.drawRect(0, 0, 50, 50);
  DecreasedWorldSuck.Icon.graphics.beginBitmapFill(new Heart2());
  DecreasedWorldSuck.Icon.graphics.drawRect(0, 0, 50 ,50);

  SaveTheWorld = new AchievementBox("SaveTheWorld");
  SaveTheWorld.x = 370; SaveTheWorld.y = 50;
  SaveTheWorld.text.htmlText = "<font color='#000000'>Help 300 Million People.</font>";
  SaveTheWorld.title.htmlText = "<font size = '14' color='#000000'><u>Achievement Unlocked</u> Save The World</font>";
  SaveTheWorld.TextBackground.graphics.clear();
  SaveTheWorld.TextBackground.graphics.beginFill(0xFFFFFF);
  SaveTheWorld.TextBackground.graphics.lineStyle(1,0x000000);
  SaveTheWorld.TextBackground.graphics.drawRect(0, 0, 235, 100);
  SaveTheWorld.Icon.graphics.clear();
  SaveTheWorld.Icon.graphics.beginFill(0xFFFFFF);
  SaveTheWorld.Icon.graphics.lineStyle(1,0x000000);
  SaveTheWorld.Icon.graphics.drawRect(0, 0, 50, 50);
  SaveTheWorld.Icon.graphics.beginBitmapFill(new Heart3());
  SaveTheWorld.Icon.graphics.drawRect(0, 0, 50 ,50);

  WhiteAchievements = new List<String>();

  PerfectPair = new AchievementBox("PerfectPair");
  PerfectPair.x = 195; PerfectPair.y = 155;
  PerfectPair.text.htmlText = "<font color='#FFFFFF'>Help 300 million people and have 3 Billion+ in cash in the same game.</font>";
  PerfectPair.title.htmlText = "<font size = '14' color='#000000'><u>Achievement Unlocked</u> Perfect Pair</font>";
  PerfectPair.TextBackground.graphics.clear();
  PerfectPair.TextBackground.graphics.beginFill(0xFFFFFF);
  PerfectPair.TextBackground.graphics.lineStyle(1,0x000000);
  PerfectPair.TextBackground.graphics.drawRect(0, 0, 235, 50);
  PerfectPair.TextBackground.graphics.beginFill(0x000000);
  PerfectPair.TextBackground.graphics.lineStyle(1,0xFFFFFF);
  PerfectPair.TextBackground.graphics.drawRect(0, 50, 235, 50);
  PerfectPair.Icon.graphics.clear();
  PerfectPair.Icon.graphics.beginFill(0xFFFFFF);
  PerfectPair.Icon.graphics.lineStyle(1,0x000000);
  PerfectPair.Icon.graphics.drawRect(0, 0, 50, 50);
  PerfectPair.Icon.graphics.beginBitmapFill(new Balance2());
  PerfectPair.Icon.graphics.drawRect(0, 0, 50 ,50);

  MoreThanBalance = new AchievementBox("MoreThanBalance");
  MoreThanBalance.x = 195; MoreThanBalance.y = 155;
  MoreThanBalance.text.htmlText = "<font color='#FFFFFF'>Recieve a balance of 0.5 on the last turn. Well, that was pointless</font>";
  MoreThanBalance.title.htmlText = "<font size = '14' color='#000000'><u>Achievement Unlocked</u> More Than Balance</font>";
  MoreThanBalance.TextBackground.graphics.clear();
  MoreThanBalance.TextBackground.graphics.beginFill(0xFFFFFF);
  MoreThanBalance.TextBackground.graphics.lineStyle(1,0x000000);
  MoreThanBalance.TextBackground.graphics.drawRect(0, 0, 235, 50);
  MoreThanBalance.TextBackground.graphics.beginFill(0x000000);
  MoreThanBalance.TextBackground.graphics.lineStyle(1,0xFFFFFF);
  MoreThanBalance.TextBackground.graphics.drawRect(0, 50, 235, 50);
  MoreThanBalance.Icon.graphics.clear();
  MoreThanBalance.Icon.graphics.beginFill(0xFFFFFF);
  MoreThanBalance.Icon.graphics.lineStyle(1,0x000000);
  MoreThanBalance.Icon.graphics.drawRect(0, 0, 50, 50);
  MoreThanBalance.Icon.graphics.beginBitmapFill(new Balance1());
  MoreThanBalance.Icon.graphics.drawRect(0, 0, 50 ,50);

  BothAchievements = new List<String>();

  EndGame = new Sprite();
  EndGame.graphics.beginFill(0xFFFFFF);
  EndGame.graphics.lineStyle(1,0x000000);
  EndGame.graphics.drawRect(0, 0, 300, 260);
  EndGame.x =170; EndGame.y = 70;
  var EndGameTitle = new TextField();
  EndGameTitle.htmlText = "<font size='20'><u>End Game</u></font>";
  EndGameTitle.width = 300;
  EndGameTitle.y = 10;
  EndGameTitle.autoSize = TextFieldAutoSize.CENTER;
  EndGame.addChild(EndGameTitle);
  EndGameMoneyEarned = new TextField();
  EndGameMoneyEarned.htmlText = "<font size='16'>Money: XXXXX</font>";
  EndGameMoneyEarned.y = 60;
  EndGameMoneyEarned.width = 300;
  EndGameMoneyEarned.autoSize = TextFieldAutoSize.CENTER;
  EndGame.addChild(EndGameMoneyEarned);
  EndGamePeopleHelped = new TextField();
  EndGamePeopleHelped.htmlText = "<font size='16'>People Helped: XXXXX</font>";
  EndGamePeopleHelped.y = 110;
  EndGamePeopleHelped.width = 300;
  EndGamePeopleHelped.autoSize = TextFieldAutoSize.CENTER;
  EndGame.addChild(EndGamePeopleHelped);

  EndGameRetry = new Sprite();
  EndGameRetry.graphics.beginFill(0x000000);
  EndGameRetry.graphics.lineStyle(1,0xFFFFFF);
  EndGameRetry.graphics.drawRect(0, 0, 135, 80);
  EndGameRetry.x = 10; EndGameRetry.y = 170;
  EndGameRetry.buttonMode = true;
  EndGameRetry.addEventListener(MouseEvent.CLICK, onRetryClick);
  EndGame.addChild(EndGameRetry);
  var EndGameRetryText = new TextField();
  EndGameRetryText.htmlText = "<font size='16' color ='#FFFFFF'>Retry</font>";
  EndGameRetryText.y = 25;
  EndGameRetryText.width = 135;
  EndGameRetryText.autoSize = TextFieldAutoSize.CENTER;
  EndGameRetryText.mouseEnabled = false;
  EndGameRetryText.selectable =false;
  EndGameRetry.addChild(EndGameRetryText);


  EndGameMainMenu = new Sprite();
  EndGameMainMenu.graphics.beginFill(0xFFFFFF);
  EndGameMainMenu.graphics.lineStyle(1,0x000000);
  EndGameMainMenu.graphics.drawRect(0, 0, 135, 80);
  EndGameMainMenu.x = 155; EndGameMainMenu.y = 170;
  EndGameMainMenu.buttonMode = true;
  EndGameMainMenu.addEventListener(MouseEvent.CLICK, onMainMenuClick);
  EndGame.addChild(EndGameMainMenu);
  var EndGameMainMenuText = new TextField();
  EndGameMainMenuText.htmlText = "<font size='16'>Main Menu</font>";
  EndGameMainMenuText.y = 25;
  EndGameMainMenuText.width = 135;
  EndGameMainMenuText.autoSize = TextFieldAutoSize.CENTER;
  EndGameMainMenuText.mouseEnabled = false;
  EndGameMainMenuText.selectable =false;
  EndGameMainMenu.addChild(EndGameMainMenuText);
  

  mKeyDown = [];
  lastUp = Keyboard.RIGHT;
  
  TurnLeft = new TextField();
  playersMoney = new TextField();
  playersPeopleHelped = new TextField();
  swedishBankAccount = new TextField();

  Player = new CharacterStat(); 
  Player.Money = 0;
  Player.PeopleHelped = 0; 
  Player.addEventListener("updateValues",updateValues);

  }

public function drawBackground()
{
    backgroundLayer.removeChild(currentBackground);
      currentBackground = new CustomSprite();
    
      currentBackground.graphics.beginFill(0x000000);
      //Grid.graphics.drawRect(0, 0,620-150,472);
      currentBackground.graphics.drawRect(0, 0, (Ratio *(Constants.flashWidth)),Constants.flashHeight-20);
      currentBackground.graphics.beginFill(0xFFFFFF);
      currentBackground.graphics.drawRect((Ratio *(Constants.flashWidth)), 0,(1-Ratio) *(Constants.flashWidth),Constants.flashHeight-20);
      currentBackground.graphics.endFill();
//     if(Ratio >=1)
//     {
//       currentBackground = new CustomSprite();
//       currentBackground.graphics.beginFill(0x000000);
//       //Grid.graphics.drawRect(0, 0,620-150,472);
//       currentBackground.graphics.drawRect(0, 0, (1*(Constants.flashWidth))-(1/Ratio *(Constants.flashWidth/2)),Constants.flashHeight-20);
//       currentBackground.graphics.beginFill(0xFFFFFF);
//       currentBackground.graphics.drawRect( (1*(Constants.flashWidth))-(1/Ratio *(Constants.flashWidth/2)), 0, (1/Ratio *(Constants.flashWidth/2)),Constants.flashHeight-20);
//       currentBackground.graphics.endFill();
//     }
//     else
//     {
//       currentBackground = new CustomSprite();
//     
//       currentBackground.graphics.beginFill(0x000000);
//       //Grid.graphics.drawRect(0, 0,620-150,472);
//       currentBackground.graphics.drawRect(0, 0, (Ratio *(Constants.flashWidth/2)),Constants.flashHeight-20);
//       currentBackground.graphics.beginFill(0xFFFFFF);
//       currentBackground.graphics.drawRect((Ratio *(Constants.flashWidth/2)), 0,(1*(Constants.flashWidth))-(Ratio *(Constants.flashWidth/2)),Constants.flashHeight-20);
//       currentBackground.graphics.endFill();
//     }
    backgroundLayer.addChild(currentBackground);
    var Greed = new TextField();
    Greed.htmlText = "<font size='24' color='#FFFFFF'>Greed</font>";
    Greed.x = 20;
    currentBackground.addChild(Greed);
    var Charity= new TextField();
    Charity.htmlText = "<font size='24'>Charity</font>";
    Charity.x = 540;
    currentBackground.addChild(Charity);

    if(stage != null)
    {
    stage.focus = stage;
    }
}

//Load Level, so that it isn't automatically loaded automatically.
public function Load(inVolume:Bool,inSound:Bool,inContine:Bool)
{
  MenuUp = false;
  volume = inVolume;
  sound = inSound;

  running = true;
  flash.Lib.current.addChild(this);
  addChild(backgroundLayer);
  //addChild(WorkCoButton);
  WorkCoButton.addEventListener(MouseEvent.CLICK, onWorkCoButtonClick);
  addChild(WallStreetButton);
  WallStreetButton.addEventListener(MouseEvent.CLICK, onWallStreetButtonClick);
  addChild(CharityButton);
  CharityButton.addEventListener(MouseEvent.CLICK, onCharityButtonClick);
  var nextTurnButton = new Sprite();
  nextTurnButton.graphics.lineStyle(1);
  nextTurnButton.graphics.drawRect(0, 0,60,20);
  nextTurnButton.graphics.beginFill(0xFFFFFF);
  var text = new TextField();
  text.htmlText = "<u>N</u>ext Week";
  text.width = 60; text.height = 20;
  text.selectable = false;
  text.mouseEnabled = false;
  nextTurnButton.addChild(text);
  nextTurnButton.x = 540; nextTurnButton.y = 405;
  nextTurnButton.buttonMode = true;
  nextTurnButton.addEventListener(MouseEvent.CLICK, onNextTurnButtonClick);
  addChild(nextTurnButton);
  
  PlayerStat = new TextField();
  addChild(PlayerStat);
  PlayerStat.x = 10;
  PlayerStat.y = 410;
  PlayerStat.width = 540;
  PlayerStat.htmlText = "Player Stats:";

  addChild(playersMoney);
  playersMoney.x = 540;
  playersMoney.y = 20; 

  addChild(playersPeopleHelped);
  playersPeopleHelped.x = 500;
  playersPeopleHelped.y = 30; 

   addChild(swedishBankAccount);
  swedishBankAccount.x = 440;
  swedishBankAccount.y = 50; 
  swedishBankAccount.height = 20;
  swedishBankAccount.width = 190;

   addChild(TurnLeft);
  TurnLeft.x = 540;
  TurnLeft.y = 40; 


  Player.Money = 1000;
  Player.PeopleHelped = 0; 
   //addhild(OkPopUp);
  
  //OkPopUpText.Load();

  //this.addEventListener(Event.ENTER_FRAME, OnEnter)
  //On Enter Was very slow on my computer. So I'm using the timer event so it doesn't render as much.
  myTimer = new Timer(25);
  myTimer.addEventListener("timer", timerHandler);
  myTimer.start();
  stage.addEventListener(KeyboardEvent.KEY_DOWN, OnKeyDown );
  stage.addEventListener(KeyboardEvent.KEY_UP, OnKeyUp );
  
  this.addEventListener("PopUpTextEvent",onPopUpTextEvent);
  this.addEventListener("PopUp",onPopUpEvent);
  this.addEventListener("AchievementBox",onAchievementBoxReturn);

//   addChild(SmallCountry);
//   addChild(PerfectPair);
//   addChild(KindHearted);
//   addChild(DecreasedWorldSuck);
//    addChild(SaveTheWorld);
//   addChild(Fortune);
//    addChild(SmallFortune);

  //addChild(EndGame);

if(inContine)
{
try
{
  var savedData = SharedObject.getLocal("GameData");
  if(savedData.data.Player != null)
  {
    Player = savedData.data.Player;
  }
  if(savedData.data.numOfTurns != null)
    {
    numOfTurns = savedData.data.numOfTurns;
    }

State = "Playing";
updateText();
Player.update();
      try
      {
      kongVar.SubmitStat("Money",Player.getBillions()*1000000 + Player.Money/1000);
      kongVar.SubmitStat("PeopleHelped",Player.PeopleHelped);
      kongVar.SubmitStat("AchievementsEarned", RecievedAchievements.getAchievementsEarned());
      }
      catch(err:Dynamic)
      {
	
      }
       if(checkEnd())
         {
         State = "EndGame";
         }
//TurnLeft.htmlText = TotalTurns - numOfTurns + 1 + " Week(s) Left";
}
catch(err:Dynamic)
{trace(err);}
}
Player.addEventListener("updateValues",updateValues);
Player.update();
}

private function isPaused():Bool{
      if(Pause != "UnPaused")
      {
	if(Pause == "Paused" || Pause == "Pausing")
          {
          addPauseMenu();
          }
        else if(Pause == "UnPausing")
         {
          removePauseMenu();
          }
         return true;
      }
      return false;
}

public function timerHandler(event:TimerEvent) {
    if(State == "RandomEvent")
    {
       //DisplayRandom Event
       //RandomEvent();
       State="Playing";
    }
    else if(State == "Wait")
    {
    }
    else if(State == "Playing")
    {
      if(isPaused())
        {return;}
      
    }
    else if(State == "EndGame")
    {
    //Show score
    //Play Again.
    if(Player.getBillions() <= 0)
    {
    EndGameMoneyEarned.htmlText = "<font size='16'>Money: $"+ HelperMethods.format(Player.Money,0) +"</font>";
    }
    else
    {
      EndGameMoneyEarned.htmlText = "<font size='16'>Money: $"+ HelperMethods.formatFloat((Player.getBillions() + (Player.Money/(1000000000))),5) +" Billion(s)</font>";
    }
    EndGamePeopleHelped.htmlText = "<font size='16'>People Helped: "+  HelperMethods.format(Player.PeopleHelped,0) +"</font>";
    addChild(EndGame);
    //unLoad();
    }
    else if (State == "Calc")
    {
//        var test = 0;
//        trace(test);
//        test = test + Std.int(2000000000+1);
//        trace(test);
//        trace(test*100);
//        trace(test*10000);
//        test = test*10000 + 10000000;
//        trace(test);
      //Player.Money += 500000000;
       var SumMoney = 0;
       var SumPeopleHelped = 0;
       var Sum = false;
       var length = 0;
       for(income in Player.Income.iterator())
       {
          
           if (length > 15)
           { Sum = true;}
           length++;
            if(income.Lengivity >= 1)
              {income.Lengivity--;} 
            var Money = Std.int(income.Money + Std.random(income.RandomMoney));
            if(Money  != 0)
              {
            if(Sum)
		{
		  SumMoney += Money;
		  Player.setMoneyWithoutEvent(Money);
		}
            else
                {
		var text : FadingText = new FadingText();
		var textString = "$"+Money;
		var prevMoney = Player.Money;
		Player.Money += Money;
	      
		text.x = Std.random(620)+10; text.y = Std.random(400)+10;
		text.htmlText = "<font color='#000000'>"+textString+"</font>";
		if(text.x < currentBackground.width/2)
		{
		text.htmlText = "<font color='#FFFFFF'>"+textString+"</font>";
		text.x = (Math.min(text.x, ((currentBackground.width /2) - text.width)));
		}
		// text.height = 25;
		text.start();
                 }
             }
            var PeopleHelped = Std.int(income.PeopleHelped + Std.random(income.RandomPeopleHelped));
            if(PeopleHelped != 0 )
              {
            if(Sum)
		{
		  SumPeopleHelped += PeopleHelped;
		  Player.setPeopleHelpedWithoutEvent(PeopleHelped);
		}
            else
	      {
	      var text : FadingText = new FadingText();
	      text.htmlText = PeopleHelped + " People Helped" ;
	      Player.PeopleHelped += PeopleHelped;
	      text.x = Std.random(620)+10; text.y = Std.random(400)+10;
	      // text.height = 25;
	      text.start();
	      }
             }
             if(income.Lengivity == 0)
               {
               Player.Income.remove(income);
               }
       }
       if(Sum)
         {

		var text : FadingText = new FadingText();
		text.htmlText = "$"+SumMoney;
		//Player.Money += SumMoney;
		Player.update();
		text.x = Std.random(620)+10; text.y = Std.random(400)+10;
		// text.height = 25;
		text.start();

	      var text : FadingText = new FadingText();
	      text.htmlText = SumPeopleHelped + " People Helped" ;
	      Player.update();
	      //Player.PeopleHelped += SumPeopleHelped;
	      text.x = Std.random(620)+10; text.y = Std.random(400)+10;
	      // text.height = 25;
	      text.start();


         }
//        playersMoney.htmlText = "$"+Player.Money;
//        playersPeopleHelped.htmlText = Player.PeopleHelped + "People Helped" ; 
      //TurnLeft.htmlText = TotalTurns - numOfTurns + " Week(s) Left";
       numOfTurns++;
       updateText();
       ResetTurnVariables();
       State = "Playing";
	var savedData = SharedObject.getLocal("GameData");
	savedData.data.numOfTurns = numOfTurns;
	savedData.data.Player = Player;
	savedData.flush();

      try
      {
      kongVar.SubmitStat("Money",Player.getBillions()*1000000 + Player.Money/1000);
      kongVar.SubmitStat("PeopleHelped",Player.PeopleHelped);
      kongVar.SubmitStat("AchievementsEarned", RecievedAchievements.getAchievementsEarned());
      }
      catch(err:Dynamic)
      {
	
      }
       if(checkEnd())
         {
         State = "EndGame";
	    try
	    {
	    kongVar.SubmitStat("FinishedGame",1);
	    }
	    catch(err:Dynamic)
	    {
	    }
         }
      var MoneyAssests = Player.Money;
      var ExtraBillion = 0;
      for(income in Player.Income)
      {
	if(income.Title == "Investment")
	{
	  MoneyAssests += income.Value;
	  if(MoneyAssests >= 1500000000)
	  {
	    MoneyAssests - 1000000000;
	    ExtraBillion += 1;
	  }
	}
      }
      ExtraBillion += Player.getBillions();
      var getBlackAchievement = false;

      if(Player.Money > 10000000 ||  Player.getBillions() > 0) 
      {
	if(!RecievedAchievements.SmallFortune)
	{
	    BlackAchievements.add("SmallFortune");
	    RecievedAchievements.SmallFortune = true;
	    getBlackAchievement = true;
	}
      }
      if(Player.Money > 500000000 ||  Player.getBillions() > 0) 
      {
	if(!RecievedAchievements.Fortune)
	{
	    BlackAchievements.add("Fortune");
	    RecievedAchievements.Fortune = true;
	    getBlackAchievement = true;
	}
      }
      if(Player.getBillions() + (Player.Money/1000000000) >= 3) 
      {
      
	if(!RecievedAchievements.SmallCountry)
	{
	    BlackAchievements.add("SmallCountry");
	    RecievedAchievements.SmallCountry = true;
	    getBlackAchievement = true;
	}
      }
      if(getBlackAchievement)
      {
	GetBlackAchievement();
      }

      var getWhiteAchievement = false;

      if(Player.PeopleHelped > 100000) 
      {
	if(!RecievedAchievements.KindHearted)
	{
	    WhiteAchievements.add("KindHearted");
	    RecievedAchievements.KindHearted = true;
	    getWhiteAchievement = true;
	}
      }
      if(Player.PeopleHelped > 10000000) 
      {
	if(!RecievedAchievements.DecreasedWorldSuck)
	{
	    WhiteAchievements.add("DecreasedWorldSuck");
	    RecievedAchievements.DecreasedWorldSuck = true;
	    getWhiteAchievement = true;
	}
      }
      if(Player.PeopleHelped >= 300000000) 
      {
      
	if(!RecievedAchievements.SaveTheWorld)
	{
	    WhiteAchievements.add("SaveTheWorld");
	    RecievedAchievements.SaveTheWorld = true;
	    getWhiteAchievement = true;
	}
      }
      if(getWhiteAchievement)
      {
	GetWhiteAchievement();
      }
    

      var getBothAchievement = false;

      if(Player.PeopleHelped >= 300000000 && Player.getBillions() + (Player.Money/1000000000) >= 3) 
      {
	if(!RecievedAchievements.PerfectPair)
	{
	    BothAchievements.add("PerfectPair");
	    RecievedAchievements.PerfectPair = true;
	    getBothAchievement = true;
	}
      }
      if(TotalTurns-numOfTurns == 0 && Ratio == .5)
      {
	if(!RecievedAchievements.MoreThanBalance)
	{
	    BothAchievements.add("MoreThanBalance");
	    RecievedAchievements.MoreThanBalance = true;
	    getBothAchievement = true;
	}
      }
      if(getBothAchievement)
      {
	GetBothAchievement();
      }
      
	
      	var achievementsData = SharedObject.getLocal("AchievementsData");
	achievementsData.data.Achievements = RecievedAchievements;
	achievementsData.flush();

	drawBackground();
      //Calc Money in, Determine if there is any Random Event
      //Calculate.
      
    }
}

public function ResetTurnVariables()
{
  searchedForJob = false;
}
public function GetBlackAchievement()
{
  var blackChild = BlackAchievements.pop();
  if(blackChild == "SmallFortune")
  {
    addChild(SmallFortune);
    if(sound)
    {
      achievementNoise.play();
    }
  }
  else if(blackChild == "Fortune")
  {
    addChild(Fortune);
    if(sound)
    {
      achievementNoise.play();
    }
  }
  else if (blackChild == "SmallCountry")
  {
    addChild(SmallCountry);
    if(sound)
    {
      achievementNoise.play();
    }
  }
}

public function GetWhiteAchievement()
{
  var whiteChild = WhiteAchievements.pop();
  if(whiteChild == "KindHearted")
  {
    addChild(KindHearted);
    if(sound)
    {
      achievementNoise.play();
    }
  }
  else if(whiteChild == "DecreasedWorldSuck")
  {
    addChild(DecreasedWorldSuck);
    if(sound)
    {
      achievementNoise.play();
    }
  }
  else if (whiteChild == "SaveTheWorld")
  {
    addChild(SaveTheWorld);
    if(sound)
    {
      achievementNoise.play();
    }
  }
}

public function GetBothAchievement()
{
  var bothChild = BothAchievements.pop();
  if(bothChild == "PerfectPair")
  {
    if(sound)
    {
      achievementNoise.play();
    }
    addChild(PerfectPair);
  }
  else if(bothChild == "MoreThanBalance")
  {
    addChild(MoreThanBalance);
    if(sound)
    {
      achievementNoise.play();
    }
  }
}


public function updateText()
{
      var variance = 0.000001;
      var MoneyToPeopleHelped = 100;
      try
      {
      //Ratio = (Math.max((Player.Money/100)-9,1))/(Player.PeopleHelped+1);
      var MoneyAssests = Player.Money;
      var ExtraBillion = 0;
      for(income in Player.Income)
      {
	if(income.Title == "Investment")
	{
	  MoneyAssests += income.Value;
	  if(MoneyAssests >= 1500000000)
	  {
	    MoneyAssests - 1000000000;
	    ExtraBillion += 1;
	  }
	}
      }
      var BankAssests = ((Player.getBillions()+ExtraBillion))*((1000000000/MoneyToPeopleHelped)*variance);
      Ratio = 0.5 +  ((((Math.max((MoneyAssests/MoneyToPeopleHelped)-((1000/MoneyToPeopleHelped)-1),1))*variance)+BankAssests) - ((Player.PeopleHelped+1)*variance));
// /*      OkPopUp.text.htmlText = "BankAssests: " + BankAssests + " Money Asssets: " + ((Math.max((MoneyAssests/10)-99,1))*variance) + " People Helped: " + ((Player.PeopleHelped+1)*variance) ;
//       addChild(OkPopUp)*/;
      //Ratio = Math.min(Ratio,1);
      //Ratio = Math.max(Ratio,0);
      
      PlayerStat.htmlText = "Player Stats:" + " $"+ HelperMethods.format(Player.Money,0) + " People Helped: " + HelperMethods.format(Player.PeopleHelped,0) ;
      playersMoney.htmlText = "";
      //playersPeopleHelped.htmlText = Player.PeopleHelped + " People Helped" ;
      if(Player.getBillions() > 0)
        {
	  PlayerStat.htmlText += " Swedish Bank Account: " + Player.getBillions() + " billion";
        }
      PlayerStat.htmlText +=  " You Have " + Std.int(TotalTurns - numOfTurns + 1) + " Week(s) Left";
      //PlayerStat.htmlText += " Percentage: " + Ratio;
      }
      catch(msg:Dynamic)
      {
       trace("MESSAGE " + msg);
      }
}
public function updateValues(e:Event)
{
  updateText();
}

private function onRetryClick(event:MouseEvent) {
  dispatchEvent(new Event("LevelRetry"));
}
private function onMainMenuClick(event:MouseEvent) {
  dispatchEvent(new Event("LevelReturn"));
}
private function onNextTurnButtonClick(event:MouseEvent) {
if(State == "Playing"){
  State = "Calc";
  }
}


private function onWorkCoButtonClick(event:MouseEvent) {
  WorkCoMenuItem.addEventListener("Back",onWorkCoMenuItemBack);
 // WorkCoMenuItem.addEventListener("FindJob",onWorkCoMenuItemFindJob);
  addChild(WorkCoMenuItem);
}

private function onWallStreetMenuItemFindJob(event:WallStreetMenuEvent)
{
    FindJob();

}
private function FindJob()
{
  if(searchedForJob)
    return;

  if(!searchedForJob)
    {
    searchedForJob = true;
    
    }
   if(Std.random(100) < 3)
     {
      OkPopUp = new PopUp(null,"<font color='#FFFFFF'>You didn't find a Job",0x000000,0xFFFFFF);
      addChild(OkPopUp);
     }
   else
     {
        //Found Job
        var Income:Int;
        Income = Std.int((20000 * ((numOfTurns/20)+1) + Std.random(1000))/40);
       for(income in Player.Income.iterator())
       {
        if(income.Title == "Job")
          {
            Player.Income.remove(income); 
          }
       }
       var job = new IncomeMethod();
       
       job.Title = "Job";
       job.Lengivity = -1;
       job.Money = Income;

       Player.Income.add(job);
       OkPopUp = new PopUp(null,"<font color='#FFFFFF'>You Found a Job For $" + Income + "/week</font>",0x000000,0xFFFFFF);
       addChild(OkPopUp);

        
     }
}
private function onWorkCoMenuItemBack(event:GenericMenuEvent)
{
WorkCoMenuItem.removeEventListener("Back",onWorkCoMenuItemBack);
 // WorkCoMenuItem.removeEventListener("FindJob",onWorkCoMenuItemBack);
  removeChild(WorkCoMenuItem);
stage.focus = stage;
}

private function onWallStreetMenuItemBack(event:GenericMenuEvent)
{
WallStreetMenuItem.removeEventListener("Back",onWallStreetMenuItemBack);
  WallStreetMenuItem.removeEventListener("SmallBusiness",onWallStreetMenuItemSmallBusiness);
  WallStreetMenuItem.removeEventListener("MediumBusiness",onWallStreetMenuItemMediumBusiness);
  WallStreetMenuItem.removeEventListener("LargeBusiness",onWallStreetMenuItemLargeBusiness);
  WallStreetMenuItem.removeEventListener("StockMarket",onWallStreetMenuItemPopUpTextEvent);
  WallStreetMenuItem.removeEventListener("FindJob",onWallStreetMenuItemFindJob);
WallStreetMenuItem.removeEventListener("ignoreKeyPress",onWallStreetMenuItemIgnoreKeyPress);
  removeChild(WallStreetMenuItem);
  MenuUp = false;
stage.focus = stage;
}
private function onWallStreetButtonClick(event:MouseEvent) {
  WallStreetMenuItem.addEventListener("Back",onWallStreetMenuItemBack);
  WallStreetMenuItem.addEventListener("SmallBusiness",onWallStreetMenuItemSmallBusiness);
  WallStreetMenuItem.addEventListener("MediumBusiness",onWallStreetMenuItemMediumBusiness);
  WallStreetMenuItem.addEventListener("LargeBusiness",onWallStreetMenuItemLargeBusiness);
  WallStreetMenuItem.addEventListener("StockMarket",onWallStreetMenuItemPopUpTextEvent);
  WallStreetMenuItem.addEventListener("FindJob",onWallStreetMenuItemFindJob);
  WallStreetMenuItem.addEventListener("ignoreKeyPress",onWallStreetMenuItemIgnoreKeyPress);
  addChild(WallStreetMenuItem);
  MenuUp = true;
}

private function onWallStreetMenuItemSmallBusiness(event:WallStreetMenuEvent)
{
    ignoreKeyPress = "";
    try
    {
    var Number = Std.parseInt(event.Number);
    BuyBusiness(Number,10000,200,"Small");
    }
    catch(msg: Dynamic) 
    {

    }
}
private function onWallStreetMenuItemMediumBusiness(event:WallStreetMenuEvent)
{
    ignoreKeyPress = "";
    try
    {
    var Number = Std.parseInt(event.Number);
    BuyBusiness(Number,100000,4000,"Medium");
    }
    catch(msg: Dynamic) 
    {

    };
}
private function onWallStreetMenuItemLargeBusiness(event:WallStreetMenuEvent)
{
    ignoreKeyPress = "";
    try
    {
      var Number = Std.parseInt(event.Number);
      BuyBusiness(Number,1000000,80000,"Large");
    }
    catch(msg: Dynamic) 
    {

    }
}
private function onWallStreetMenuItemIgnoreKeyPress(event:WallStreetMenuEvent)
{
  ignoreKeyPress="True";
}
private function onWallStreetMenuItemPopUpTextEvent(event:WallStreetMenuEvent)
{
    ignoreKeyPress = "";
    try
    {
    var Number = Std.parseInt(event.Number);
    Invest(Number);
    }
    catch(msg: Dynamic) 
    {

    }
}

private function onCharityMenuItemBack(event:GenericMenuEvent)
{
  CharityMenuItem.removeEventListener("Back",onCharityMenuItemBack);
  CharityMenuItem.removeEventListener("SmallCharity",onCharityMenuItemSmallCharity);
  CharityMenuItem.removeEventListener("MediumCharity",onCharityMenuItemMediumCharity);
  CharityMenuItem.removeEventListener("LargeCharity",onCharityMenuItemLargeCharity);
  CharityMenuItem.removeEventListener("Give",onCharityMenuItemPopUpTextEvent);
  CharityMenuItem.removeEventListener("ignoreKeyPress",onCharityMenuItemIgnoreKeyPress);
  removeChild(CharityMenuItem);
  stage.focus = stage;
  MenuUp = false;
}
private function onCharityButtonClick(event:MouseEvent) {
  CharityMenuItem.addEventListener("Back",onCharityMenuItemBack);
  CharityMenuItem.addEventListener("SmallCharity",onCharityMenuItemSmallCharity);
  CharityMenuItem.addEventListener("MediumCharity",onCharityMenuItemMediumCharity);
  CharityMenuItem.addEventListener("LargeCharity",onCharityMenuItemLargeCharity);
  CharityMenuItem.addEventListener("Give",onCharityMenuItemPopUpTextEvent);
  CharityMenuItem.addEventListener("ignoreKeyPress",onCharityMenuItemIgnoreKeyPress);
  addChild(CharityMenuItem);
  MenuUp = true;

}

private function onCharityMenuItemSmallCharity(event:CharityMenuEvent)
{
    ignoreKeyPress = "";
    try
    {
    var Number = Std.parseInt(event.Number);
    BuySmallCharity(Number);
    }
    catch(msg: Dynamic) 
    {

    }
}
private function onCharityMenuItemMediumCharity(event:CharityMenuEvent)
{
    ignoreKeyPress = "";
    try
    {
    var Number = Std.parseInt(event.Number);
    BuyMediumCharity(Number);
    }
    catch(msg: Dynamic) 
    {

    }
}
private function onCharityMenuItemLargeCharity(event:CharityMenuEvent)
{
    ignoreKeyPress = "";
    try
    {
    var Number = Std.parseInt(event.Number);
    BuyLargeCharity(Number);
    }
    catch(msg: Dynamic) 
    {

    }
}
private function onCharityMenuItemIgnoreKeyPress(event:CharityMenuEvent)
{
  ignoreKeyPress="True";
}
private function onCharityMenuItemPopUpTextEvent(event:CharityMenuEvent)
{
    ignoreKeyPress = "";
    try
    {
    var Number = Std.parseInt(event.Number);
    Donate(Number);
    }
    catch(msg: Dynamic) 
    {

    }
}



private function onPopUpEvent(event:PopUpEvent)
{
  removeChild(OkPopUp);
  stage.focus = stage;
}

private function onAchievementBoxReturn(event:AchievementBoxEvent)
{
  if(event.Name == "SmallFortune")
  {
    removeChild(SmallFortune);
    GetBlackAchievement();
  }
  if(event.Name == "Fortune")
  {
    removeChild(Fortune);
    GetBlackAchievement();
  }
  if(event.Name == "SmallCountry")
  {
    removeChild(SmallCountry);
    GetBlackAchievement();
  }


  if(event.Name == "KindHearted")
  {
    removeChild(KindHearted);
    GetWhiteAchievement();
  }
  if(event.Name == "DecreasedWorldSuck")
  {
    removeChild(DecreasedWorldSuck);
    GetWhiteAchievement();
  }
  if(event.Name == "SaveTheWorld")
  {
    removeChild(SaveTheWorld);
    GetWhiteAchievement();
  }


 if(event.Name == "PerfectPair")
  {
    removeChild(PerfectPair);
    GetBothAchievement();
  }
  if(event.Name == "MoreThanBalance")
  {
    removeChild(MoreThanBalance);
    GetBothAchievement();
  }
}

private function onPopUpTextEvent(event:PopUpTextEvent)
{
  removeChild(OkPopUpText);
  if(ignoreKeyPress == "I")
    {
      try
      {
      var Number = Std.parseInt(event.Number);
      Invest(Number);
      }
      catch(msg: Dynamic) 
      {

      }
      ignoreKeyPress = "";
    }
  if(ignoreKeyPress == "D")
    {
      try
      {
      var Number = Std.parseInt(event.Number);
      Donate(Number);
      }
      catch(msg: Dynamic) 
      {

      }
      ignoreKeyPress = "";
    }
  if(ignoreKeyPress == "SmallBusiness")
    {
      try
      {
      var Number = Std.parseInt(event.Number);
      BuyBusiness(Number,10000,200,"Small");
      }
      catch(msg: Dynamic) 
      {

      }
      ignoreKeyPress = "";
    }
  if(ignoreKeyPress == "MediumBusiness")
    {
      try
      {
      var Number = Std.parseInt(event.Number);
      BuyBusiness(Number,100000,4000,"Medium");
      }
      catch(msg: Dynamic) 
      {

      }
      ignoreKeyPress = "";
    }
  if(ignoreKeyPress == "LargeBusiness")
    {
      try
      {
      var Number = Std.parseInt(event.Number);
      BuyBusiness(Number,1000000,80000,"Large");
      }
      catch(msg: Dynamic) 
      {

      }
      ignoreKeyPress = "";
    }
  if(ignoreKeyPress == "SmallCharity")
    {
      try
      {
      var Number = Std.parseInt(event.Number);
      BuySmallCharity(Number);
      }
      catch(msg: Dynamic) 
      {

      }
      ignoreKeyPress = "";
    }
  if(ignoreKeyPress == "MediumCharity")
    {
      try
      {
      var Number = Std.parseInt(event.Number);
      BuyMediumCharity(Number);
      }
      catch(msg: Dynamic) 
      {

      }
      ignoreKeyPress = "";
    }
  if(ignoreKeyPress == "LargeCharity")
    {
      try
      {
      var Number = Std.parseInt(event.Number);
      BuyLargeCharity(Number);
      }
      catch(msg: Dynamic) 
      {

      }
      ignoreKeyPress = "";
    }
stage.focus = stage;
  
}

public function Invest(Number:Int)
{
if(Number > Player.Money)
  {
   OkPopUp = new PopUp(null,"<font color='#FFFFFF'>You don't have that much</font>",0x000000,0xFFFFFF);
   addChild(OkPopUp);
  }
else if(Number <= 0)
  {
   OkPopUp = new PopUp(null,"<font color='#FFFFFF'>Must be Postive</font>",0x000000,0xFFFFFF);
   addChild(OkPopUp);
  }
else if (Number > 500000000)
  {
     OkPopUp= new PopUp(null,"<font color='#FFFFFF'>Stock Regulations prevent you from invest more than $500,000,000. Sorry.</font>",0x000000,0xFFFFFF);
     addChild(OkPopUp);
  }
else
  {
    Player.Money -= Number;
    var stock = new IncomeMethod();
       
       stock.Title = "Investment";
       stock.Lengivity = -1;
       stock.Money = Std.int(-Number/4);
       stock.Value = Number;
      stock.RandomMoney = Std.int(.75 * Number);
      Player.Income.add(stock);
  }
}

public function Donate(Number:Int)
{
if(Number > Player.Money)
  {
  OkPopUp = new PopUp(null,"You don't have that much");
   addChild(OkPopUp);
  }
else if(Number <= 0)
  {
  OkPopUp = new PopUp(null,"Must be Postive");
   addChild(OkPopUp);
  }
else if (Number > 500000000)
  {
    OkPopUp = new PopUp(null,"Government Regulations prevent you from donating more than $500,000,000 at a time. Sorry.");
     addChild(OkPopUp);
  }
else
  {
    Player.Money -= Number;
    var donation = new IncomeMethod();
       
       donation.Title = "Donation";
       donation.Lengivity = 1;
       donation.PeopleHelped = Std.int(Number / 100);
       donation.Value = Number;

      Player.Income.add(donation);
  }
}



private function BuyBusiness(number:Int,Cost:Int,Output:Int,text:String)
{
var numofBusinesses = 0;
number = Std.int(Math.min(number,1000));
for(i in 0...number)
{
if(Player.Money < Cost && i == 0)
  {
      OkPopUp = new PopUp(null,"<font color='#FFFFFF'>You need " +HelperMethods.format(Cost,0,"",",","$")+ " for a " + text + " Business</font>",0x000000,0xFFFFFF);
       addChild(OkPopUp);
      break;
  }
else if(Player.Money < Cost)
  {
      break;
  }
else
  {
       Player.Money -= Cost;
       var business = new IncomeMethod();
       
       business.Title = "Business";
       business.Lengivity = -1;
       business.Money = Output;
       business.Value = Cost;

       Player.Income.add(business);
  }
numofBusinesses = i+1;
}
  if(numofBusinesses > 0)
  {
	OkPopUp = new PopUp(null,"<font color='#FFFFFF'>You Bought " + numofBusinesses + " " + text + " Businesses</font>",0x000000,0xFFFFFF);
	addChild(OkPopUp);
  }
}

private function BuyCharity(number:Int,Cost:Int,Output:Int,text:String)
{
var numofCharities = 0;
number = Std.int(Math.min(number,1000));
for(i in 0...number)
{
if(Player.Money < Cost && i == 0)
  {
      OkPopUp = new PopUp(null,"<font color='#000000'>You need " +HelperMethods.format(Cost,0,"",",","$")+ " for a " + text + " Charity</font>");
       addChild(OkPopUp);
      break;
  }
else if(Player.Money < Cost)
  {
      break;
  }
else
  {
       Player.Money -= Cost;
       var charity = new IncomeMethod();
       
       charity.Title = "Charity";
       charity.Lengivity = -1;
       charity.PeopleHelped = Output;
       charity.Value = Cost;

       Player.Income.add(charity);
  }
numofCharities = i+1;
}
  if(numofCharities > 0)
  {
	OkPopUp = new PopUp(null,"<font color='#000000'>You Bought " + numofCharities + " " + text + " Charities</font>");
	addChild(OkPopUp);
  }
}
private function BuySmallCharity(Number:Int)
{
  BuyCharity(Number,10000,20,"Small");
}
private function BuyMediumCharity(Number:Int)
{
  BuyCharity(Number,100000,400,"Medium");
}
private function BuyLargeCharity(Number:Int)
{
  BuyCharity(Number,1000000,8000,"Large");
}

//Define Win
public function checkEnd() : Bool
{
  //End after x amount of turns,
  return(numOfTurns > TotalTurns);
}
//When we're done with the level, we'll unload in.
public function unLoad()
{
  running = false;
  try
  {
  removeChild(EndGame);
  }
  catch(err:Dynamic)
  {}
  //removeChild(new Bitmap(currentBackground));
  myTimer.stop();
  flash.Lib.current.removeChild(this);
}

public function OnKeyDown(event:KeyboardEvent)
   {
      // When a key is held down, multiple KeyDown events are generated.
      // This check means we only pick up the first one.
      if (!mKeyDown[event.keyCode])
      {
        if(ignoreKeyPress != "")
           {return;}

                  

         //Press any key to continue scence
         PauseTillKeyPressed = false;
         // Store for use in game
         mKeyDown[event.keyCode] = true;
        if(State == "Playing")
        {
//I do this here, because if they hold down P,
	 // it won't pause and unpause constantly.
	  if(mKeyDown[ 80 ] == true)
	  {
	      if(Pause == "Paused" || Pause == "Pausing")
                {
                  Pause = "UnPausing";
                }
              else 
                {
                  Pause = "Pausing";
		  pauseMenu.x = pauseMenuPoint.x;
		  pauseMenu.y = pauseMenuPoint.y;
		  addChild(pauseMenu);
                }
	  }
	  if(isPaused()){return;}
	  if(mKeyDown[49] == true)
	  {
	      OkPopUpText = new PopUpText(null,"<font color='#FFFFFF'>Enter Amount Of Small Businesses to Buy</font>",0x000000,0xFFFFFF);
              addChild(OkPopUpText);
              ignoreKeyPress = "SmallBusiness";
	  }
	  if(mKeyDown[50] == true)
	  {
	      OkPopUpText = new PopUpText(null,"<font color='#FFFFFF'>Enter Amount Of Medium Businesses to Buy</font>",0x000000,0xFFFFFF);
              addChild(OkPopUpText);
              ignoreKeyPress = "MediumBusiness";
	  }
	  if(mKeyDown[51] == true)
	  {
	      OkPopUpText = new PopUpText(null,"",0x000000,0xFFFFFF);
	      OkPopUpText.text.htmlText = "<font color='#FFFFFF'>Enter Amount Of Large Businesses to Buy</font>";
              addChild(OkPopUpText);
              ignoreKeyPress = "LargeBusiness";
	  }
	  if(mKeyDown[52] == true)
	  {
	      OkPopUpText = new PopUpText(null,"Enter Amount Of Small Charities to Buy");
              addChild(OkPopUpText);
              ignoreKeyPress = "SmallCharity";
	  }
	  if(mKeyDown[53] == true)
	  {
	      OkPopUpText = new PopUpText(null,"Enter Amount Of Medium Charities to Buy");
              addChild(OkPopUpText);
              ignoreKeyPress = "MediumCharity";
	  }
	  if(mKeyDown[54] == true)
	  {
	      OkPopUpText = new PopUpText(null,"Enter Amount Of Large Charities to Buy");
              addChild(OkPopUpText);
              ignoreKeyPress = "LargeCharity";
	      
	  }
	  if(mKeyDown[68] == true)
	  {
	      OkPopUpText = new PopUpText(null,"Enter Amount To Donate");
              addChild(OkPopUpText);
              ignoreKeyPress = "D";
	  }
	  if(mKeyDown[78] == true )
	  {
	      if(!MenuUp)
	      {
		State = "Calc";
	      }
	  }
	  if(mKeyDown[70] == true)
	  {
              FindJob();
          }
          if(mKeyDown[73] == true)
	  {
              OkPopUpText = new PopUpText(null,"<font color ='#FFFFFF'>Enter Amount To Invest</font>",0x000000,0xFFFFFF);
              addChild(OkPopUpText);
              ignoreKeyPress = "I";
          }

	}
// 	  if(mKeyDown[ 77 ] == true)
// 	  {
// 	      Mute = !Mute;
// 	  }
      }
    }
public function OnKeyUp (event:KeyboardEvent)
    {
      mKeyDown[event.keyCode] = false;
      lastUp = event.keyCode;
    }

//Pause Menu
public function addPauseMenu()
{
pauseMenu.x = pauseMenuPoint.x;
pauseMenu.y = 0;
// if(pauseMenuPoint.y <= 0)
// {
Pause = "Paused";
// } 
// if(Pause == "Pausing")
// {
//  pauseMenuPoint.y = pauseMenuPoint.y - 20;
// }
   
}
public function removePauseMenu()
{
//   pauseMenu.x = pauseMenuPoint.x;
//   pauseMenu.y = pauseMenuPoint.y;
//   if(pauseMenuPoint.y >= 380)
//   {
    Pause = "UnPaused";
    removeChild(pauseMenu);
    stage.focus = stage;
//   } 
//   if(Pause == "UnPausing")
//   {
//     pauseMenuPoint.y = pauseMenuPoint.y + 20;
//   }
}

}

